package com.evry.spring3sandbox.conf;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
public class AppConfig {
	private @Value("${jdbc.url}")
	String url;
	private @Value("${jdbc.username}")
	String username;
	private @Value("${jdbc.password}")
	String password;

	@Bean
	MessageSource messageSource() {
		ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
		ms.setBasename("messages");
		return ms;
	}

	// Resolve logical view names to .jsp resources in the /WEB-INF/views
	// directory
	@Bean
	ViewResolver viewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setViewClass(JstlView.class);
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}

	// <property name="viewClass"
	// value="org.springframework.web.servlet.view.JstlView"></property>

	@Bean(name = "transactionManager")
	DataSourceTransactionManager transactionManager() {
		DataSourceTransactionManager manager = new DataSourceTransactionManager();
		manager.setDataSource(dataSource());
		return manager;
	}

	@Bean
	DataSource dataSource() {
		BasicDataSource source = new BasicDataSource();
		source.setDriverClassName("org.hsqldb.jdbcDriver");
		source.setUrl(url);
		source.setUsername(username);
		source.setPassword(password);
		return (DataSource) source;
	}
}
